package com.yc.rpc.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yc.rpc.core.annotation.YcRpc;
import com.yc.rpc.core.client.NettyClient;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;
import java.util.UUID;
import java.util.concurrent.SynchronousQueue;

/**
 * @author 冉野 E-mail:yangtianrui135@163.com
 * @version 创建时间：2021/7/13 4:58 PM
 */
public class YcRpcInvocationHandler implements InvocationHandler {

    ApplicationContext context;

    public YcRpcInvocationHandler(ApplicationContext context) {
        this.context = context;
        nettyClient = context.getBean(NettyClient.class);
    }

    private NettyClient nettyClient ;


    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {


        Metadata personJsonObject = new Metadata();
        personJsonObject.setMethod(method.getName());
        personJsonObject.setClazz(method.getDeclaringClass().getName());
        personJsonObject.setParameterTypes(method.getParameterTypes());
        personJsonObject.setParameters(objects);
        personJsonObject.setRequestId(UUID.randomUUID().toString());

        String request = JSONObject.toJSONString(personJsonObject);
//
        System.out.println("请求服务端消息：" + request);
        String serverId = method.getDeclaringClass().getAnnotation(YcRpc.class).value();
        SynchronousQueue<String> response = nettyClient.send(serverId,personJsonObject);
        String getMsg = response.take();

        if (method.getReturnType().equals(void.class)) {
            return null;
        }
        return JSON.parseObject(getMsg, method.getReturnType());




    }
}
